<template>
  <el-form ref="formRef" :hide-required-asterisk="true" :model="form"
           :rules="rules" label-position="left" status-icon>
    <el-form-item prop="username">
      <el-input v-model="form.username" clearable placeholder="请输入用户名或手机号或邮箱" size="large">
        <template #prefix>
          <el-icon :size="23">
            <User/>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="form.password" placeholder="请输入密码" show-password size="large"
                type="password">
        <template #prefix>
          <el-icon :size="23">
            <Lock/>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button size="large" style="width: 100%" type="success" @click="doLogin(formRef)">登录</el-button>
    </el-form-item>
    <div style="display: flex;justify-content: space-between;">
      <el-button link @click="$emit('update:tab','register')">注册账号</el-button>
      <el-button link>忘记密码</el-button>
    </div>
  </el-form>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {Lock, User} from "@element-plus/icons-vue";

import {useUserStore} from "@/stores/user";
import {useRouter} from "vue-router";
import {loginAPI} from "@/apis/login";
import {ElMessage} from "element-plus";

const userStore = useUserStore()

const router = useRouter()


defineEmits(["update:tab"])


const form = reactive({
  username: '',
  password: '',
})
const rules = {
  username: [
    {required: true, message: '账号不能为空', trigger: ['blur']},
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: ['blur']}
  ]
}

const imgKaptcha = ref(null)
const urlKaptcha = "/api/common/kaptcha"


const formRef = ref(null)
// 用户登录
const doLogin = formEL => {
  formEL.validate(async (valid) => {
    if (valid) {
      let res = await loginAPI(form);
      console.log(res)
      if (res.code === 200) userStore.account = res.data
      ElMessage({
        message: "登陆成功",
        type: 'success',
        offset: window.innerHeight / 2,
      })
      let flag = true
      for (let i of res.data.authorities) {
        if (i.authority === "ADMIN") {
          flag = false;
          await router.push('/admin');
        }
      }
      if (flag) await router.push('/')
    }
  })
}

</script>

<style scoped>
.login-code {
  cursor: pointer;
}
</style>